package com.bkhc.business.repository;

import com.bkhc.business.entity.ApplyRecord;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface BusinessApplyRecordRepository extends JpaRepository<ApplyRecord,String>, JpaSpecificationExecutor<ApplyRecord> {
    default Page<ApplyRecord> findAll(ApplyRecord record, Pageable pageable){
        return findAll(new Specification<ApplyRecord>() {
            @Override
            public Predicate toPredicate(Root<ApplyRecord> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicate = new ArrayList<>();
                if(!StringUtils.isEmpty(record.getAuditPerson())){
                    predicate.add(criteriaBuilder.equal(root.get("auditPerson").as(String.class), record.getAuditPerson()));
                }
                if(!StringUtils.isEmpty(record.getAuditStatus())){
                    predicate.add(criteriaBuilder.equal(root.get("auditStatus").as(Integer.class),record.getAuditStatus()));
                }
                Predicate[] pre = new Predicate[predicate.size()];

                return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
            }
        },pageable);


    }
    @Query("select Max(m.id) from ApplyRecord  m")
    Integer generateInviteCode();
}
